/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useEffect } from "react";
import {
  Row,
  Col,
  Form,
  Button,
  Input,
  Icon,
  Popconfirm,
  Modal,
  message,
  Spin,
} from "antd";
import { connect } from "dva";
import KbPreviewImage from "@/components/KbPreviewImage";
import patterns from "@/utils/patterns";
import styles from "../style.less";
import UploadWithCrypto from "@/components/upload-width-crypto";

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};

const noop = () => {};

const PhoneFields = ({ phones = [], getFieldDecorator, onRemove }) => {
  return phones.map((field, index) => (
    <FormItem key={index} label={`电话${index + 1}`} {...formItemLayout}>
      {getFieldDecorator(`phone${index + 1}`, {
        initialValue: field,
        rules: [
          {
            ...patterns.phone,
          },
        ],
      })(
        <Input
          style={{ width: "90%", marginRight: 10 }}
          placeholder="请输入电话号码"
          allowClear
        />
      )}
      {index == phones.length - 1 &&
        index != 0 && (
          <Icon
            className="dynamic-delete-button"
            type="minus-circle-o"
            style={{ color: "red", cursor: "pointer" }}
            onClick={onRemove}
          />
        )}
    </FormItem>
  ));
};

const CustomerService = ({ form, goBack = noop, dispatch, servicePhones, servicesQrCode }) => {
  const { getFieldDecorator, validateFields, setFieldsValue, isFieldsTouched } = form;
  getFieldDecorator("phones");
  const fieldsTouched = isFieldsTouched();

  const [phones, setPhones] = useState([]);
  const [imgURL, setImgURL] = useState("");
  const [isFormChanged, setIsFormChanged] = useState(isFieldsTouched());
  const [uploading, setUploading] = useState(false);

  useEffect(
    () => {
      setIsFormChanged(fieldsTouched);
    },
    [fieldsTouched]
  );

  useEffect(
    () => {
      // 防止数据不更新
      setPhones(servicePhones.length == 0 ? [undefined] : servicePhones);
    },
    [servicePhones]
  );

  useEffect(
    () => {
      setImgURL(servicesQrCode);
    },
    [servicesQrCode]
  );

  useEffect(
    () => {
      dispatch({
        type: "wxSettings/getServiceInfo",
      });
      return () => {
        // 返回时，重置表单修改状态
        dispatch({
          type: "wxSettings/save",
          payload: {
            servicePhones: [],
          },
        });
      };
    },
    [dispatch]
  );

  const getFormValues = useCallback(
    (cb = () => {}) => {
      validateFields((err, values) => {
        if (err) return;
        const { phone1, phone2, phone3, qrCode = [] } = values;
        const { response = {} } = qrCode[0] || {};
        const { data } = response;
        const services_phone = [phone1, phone2, phone3].filter(i => i);
        cb({
          services_qrcode: data || "",
          services_phone: JSON.stringify(services_phone),
        });
      });
    },
    [validateFields]
  );

  const onSubmit = useCallback(
    () => {
      getFormValues(({ orgPhones, ...rest }) => {
        dispatch({
          type: "wxSettings/editServiceInfo",
          payload: rest,
        }).then(() => {
          dispatch({
            type: "wxSettings/getServiceInfo",
          });
          setIsFormChanged(false);
        });
      });
    },
    [getFormValues, dispatch]
  );

  const onAddField = useCallback(
    () => {
      phones.push(undefined);
      setFieldsValue({
        phones,
      });
      setPhones(phones);
    },
    [setFieldsValue, phones]
  );

  const onRemove = useCallback(
    () => {
      if (phones.length === 1) return;
      phones.pop();
      setFieldsValue({
        phones,
      });
      setPhones(phones);
      setIsFormChanged(true);
    },
    [setFieldsValue, phones]
  );

  const onGoBackClick = () => {
    if (isFormChanged) {
      Modal.confirm({
        title: "当前内容已修改，确认返回？",
        onOk: goBack,
        okText: "确认",
        cancelText: "取消",
      });
    } else {
      goBack();
    }
  };

  // 上传相关功能
  const normFile = e => {
    const { file } = e;
    // 上传前的校验
    const isLt200kb = file.size / 1024 / 1024 <= 2;
    if (!isLt200kb) {
      message.error("只能上传2MB以内的图片！");
      setImgURL("");
      return [];
    }

    // 设置上传后的图片地址
    if (file.status == "uploading") {
      setUploading(true);
    }

    if (file.status == "done") {
      const { response = {} } = file;
      setUploading(false);
      if (response.code == 0) {
        message.success("上传成功");
        setImgURL(response.data);
      } else {
        message.error(response.msg);
        return [];
      }
    }
    // 只返回最新上传的图片
    return e && [file];
  };

  const removeQrcode = useCallback(
    () => {
      setFieldsValue({
        qrCode: [],
      });
      dispatch({
        type: "wxSettings/save",
        payload: {
          servicesQrCode: "",
        },
      });
      setImgURL("");
      setIsFormChanged(true);
    },
    [setFieldsValue, dispatch]
  );

  return (
    <div className={styles.customerService}>
      <Row type="flex" justify="space-between" align="middle">
        <Col>
          <h2>联系客服</h2>
        </Col>
        <Col>
          <KbPreviewImage type="check" imgWidth={500} src="https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/customerService/concat.png">
            <a>查看示意图</a>
          </KbPreviewImage>
        </Col>
      </Row>
      <Form>
        <Row>
          <Col xs={24} md={12}>
            <h3>微信二维码</h3>
            <Row type="flex" justify="center" align="middle">
              <Col>
                <FormItem>
                  {getFieldDecorator("qrCode", {
                    valuePropName: "fileList",
                    getValueFromEvent: normFile,
                  })(
                    <UploadWithCrypto
                      name="img"
                      listType="picture-card"
                      className="avatar-uploader"
                      action="/Api/CustomerService/uploadImage"
                      accept="image/png,image/jpg,image/jpeg"
                      showUploadList={false}
                    >
                      <Spin spinning={uploading}>
                        {imgURL ? (
                          <img src={imgURL} alt="avatar" style={{ width: "100%" }} />
                        ) : (
                          <div>
                            <Icon type="plus" />
                            <div className="ant-upload-text">上传二维码</div>
                          </div>
                        )}
                      </Spin>
                    </UploadWithCrypto>
                  )}
                  <Row>
                    {imgURL && (
                      <>
                        <Col span={12}>
                          <a style={{ cursor: "unset" }}>点击图片重新上传</a>
                        </Col>
                        <Col>
                          <a style={{ cursor: "pointer", color: "red" }} onClick={removeQrcode}>
                            删除
                          </a>
                        </Col>
                      </>
                    )}
                    <Col style={{ color: "#F6A64A" }}>
                      注：若上传群二维码，有效期只有7天，需要定期更换
                    </Col>
                  </Row>
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col xs={24} md={12}>
            <h3>添加电话</h3>
            <Row gutter={[20, 20]}>
              <Col>
                <PhoneFields
                  phones={phones}
                  getFieldDecorator={getFieldDecorator}
                  onRemove={onRemove}
                />
              </Col>
              <Col>
                <FormItem {...formItemLayoutWithOutLabel}>
                  <Button
                    disabled={phones.length == 3}
                    type="dashed"
                    style={{ width: "90%" }}
                    onClick={onAddField}
                  >
                    <Icon type="plus" /> 添加电话
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Col>
        </Row>
      </Form>
      <Row
        type="flex"
        justify="end"
        style={{ marginTop: 20 }}
        gutter={[30, 30]}
        className={styles.customizedMenu__bottom}
      >
        <Col>
          <Popconfirm title="确认保存当前信息？" onConfirm={onSubmit} disabled={!isFormChanged}>
            <Button type="primary" disabled={!isFormChanged}>
              保存
            </Button>
          </Popconfirm>
        </Col>
        <Col>
          <Button type="primary" onClick={onGoBackClick}>
            返回
          </Button>
        </Col>
      </Row>
    </div>
  );
};

export default connect(({ wxSettings }) => ({
  servicesQrCode: wxSettings.servicesQrCode,
  servicePhones: wxSettings.servicePhones,
}))(
  React.memo(
    Form.create({
      mapPropsToFields: ({ servicesQrCode }) => {
        const fileList = [];
        if (servicesQrCode) {
          fileList.push({
            response: {
              data: servicesQrCode,
            },
          });
        }
        return {
          qrCode: Form.createFormField({
            value: fileList,
          }),
        };
      },
    })(CustomerService)
  )
);
